package com.sqly.doc.menu.qianyue;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.fwjh.fwjh_add;
import com.sqly.doc.pojo.Doctor;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.ServicePackage;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;
import com.sqly.doc.view.XListView;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.view.PieChartView;

public class qianyue_list extends MyBaseActivity {

    private int[] colorData = {Color.parseColor("#FF4500"), Color.parseColor("#87CEFF")};
    private String[] stateChar = {"已签约", "未签约"};
    PieChartView bzfx;
    protected PieChartData pieChardata;
    List<PointValue> v1;

    LinearLayout l1, l2;//内容布局
    ImageView img1, img2, img3;//图表组
    TextView tv_wqy, tv_yqy, tv_tj;//菜单文字组
    String[] bqcolor;//统计标签列表
    Context context = qianyue_list.this;
    List<ServicePackage> servicelist;//服务包列表数据
    ListView qylistView;//统计如表标签

    private int pageNum1 = 1;// 无关键字页数
    List<JuMin> list;//信息列表
    XListView listView;//居民列表
    String flag = "0";
    ImageView add;
    EditText key;
    List<Doctor> dlist;
    Spinner keynf1, keynf2;
    private List<String> nfdata = new ArrayList<>();
    String nf1= DateConvert.yearofday()+"",nf2=  DateConvert.yearofday()+"";
    ImageView cx1, cx2;//
    TextView nftext1,csrq;
    private String url = HttpUrl.GetNotSignedUser;

    @Override
    public void onResume() {
        super.onResume();
        pageNum1 = 1;
        getJumin(flag);
    }

    @Override
    protected void initUI() {
        setContentView(R.layout.qianyue_list);
        //实例化控件信息
        initView();
        //实例化监听
        initListener();
        //gettongji();//获取服务包内容
    }

    @Override
    protected void initData() {

    }

    public void initView() {
        qylistView=(ListView)findViewById(R.id.qylistView);
        bzfx=(PieChartView)findViewById(R.id.bzfx);
        add = (ImageView) findViewById(R.id.add);
        key = (EditText) findViewById(R.id.key);
        nftext1 = (TextView) findViewById(R.id.nftext1);
        keynf1= (Spinner) findViewById(R.id.keynf1);
        keynf2= (Spinner) findViewById(R.id.keynf2);
        cx1= (ImageView) findViewById(R.id.cx1);
        cx2= (ImageView) findViewById(R.id.cx2);
        l1 = (LinearLayout) findViewById(R.id.l1);
        l2 = (LinearLayout) findViewById(R.id.l2);
        img1 = (ImageView) findViewById(R.id.img1);
        img2 = (ImageView) findViewById(R.id.img2);
        img3 = (ImageView) findViewById(R.id.img3);
        tv_wqy = (TextView) findViewById(R.id.tv_wqy);
        tv_yqy = (TextView) findViewById(R.id.tv_yqy);
        tv_tj = (TextView) findViewById(R.id.tv_tj);
        listView = (XListView) findViewById(R.id.listView);
        csrq =  (TextView) findViewById(R.id.csrq);
        listView.setPullLoadEnable(true);

        nftext1.setVisibility(View.GONE);
        keynf1.setVisibility(View.GONE);
        ///签约年限

        for(int i=DateConvert.yearofday()-1; i<=DateConvert.yearofday(); i++) {
            nfdata.add(""+i);
        }
        keynf1.setAdapter(new CommonAdapter<String>(context, nfdata, R.layout.sp_item) {
            @Override
            public void convert(ViewHolder helper, String item) {
                helper.setText(R.id.name, item);
            }
        });
        keynf1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0){
                    nf1 = ""+(DateConvert.yearofday()-1);
                }else{
                    nf1 = ""+(DateConvert.yearofday()+(position-1));
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        keynf1.setSelection(1);

        keynf2.setAdapter(new CommonAdapter<String>(context, nfdata, R.layout.sp_item) {
            @Override
            public void convert(ViewHolder helper, String item) {
                helper.setText(R.id.name, item);
            }
        });
        keynf2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0){
                    nf2 = ""+(DateConvert.yearofday()-1);
                }else{
                    nf2 = ""+(DateConvert.yearofday()+(position-1));
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        keynf2.setSelection(1);
        //getJumin(1);
    }

    public void initListener() {
        key.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        cx1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getJumin(flag);
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtils.isEmpty(SharedPreferencesUtils.getParam(context, "token", "").toString())) {
                    Bundle b = new Bundle();
                    b.putSerializable("juMin", null);
                    startActivity(new Intent(context, qianyue_add.class).putExtras(b));
                }
            }
        });
        tv_wqy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_wqy.setTextColor(Color.parseColor("#008B8B"));
                img1.setImageResource(R.mipmap.myqy2);
                tv_yqy.setTextColor(Color.parseColor("#8A8A8A"));
                img2.setImageResource(R.mipmap.yjqy1);
                tv_tj.setTextColor(Color.parseColor("#8A8A8A"));
                img3.setImageResource(R.mipmap.tj2);
                l1.setVisibility(View.VISIBLE);
                l2.setVisibility(View.GONE);
                nftext1.setVisibility(View.GONE);
                keynf1.setVisibility(View.GONE);
                csrq.setText("出生日期");
                pageNum1 = 1;
                flag = "0";
                url = HttpUrl.GetNotSignedUser;
                getJumin(flag);
            }
        });
        tv_yqy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_yqy.setTextColor(Color.parseColor("#008B8B"));
                img1.setImageResource(R.mipmap.myqy1);
                tv_wqy.setTextColor(Color.parseColor("#8A8A8A"));
                img2.setImageResource(R.mipmap.yjqy2);
                tv_tj.setTextColor(Color.parseColor("#8A8A8A"));
                img3.setImageResource(R.mipmap.tj2);
                l1.setVisibility(View.VISIBLE);
                l2.setVisibility(View.GONE);
                nftext1.setVisibility(View.VISIBLE);
                keynf1.setVisibility(View.VISIBLE);
                csrq.setText("签约日期");
                pageNum1 = 1;
                flag = "1";
                url = HttpUrl.GetSignedUser;
                getJumin(flag);
            }
        });
        tv_tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_tj.setTextColor(Color.parseColor("#008B8B"));
                img1.setImageResource(R.mipmap.myqy1);
                tv_wqy.setTextColor(Color.parseColor("#8A8A8A"));
                img2.setImageResource(R.mipmap.yjqy1);
                tv_yqy.setTextColor(Color.parseColor("#8A8A8A"));
                img3.setImageResource(R.mipmap.tj1);
                l1.setVisibility(View.GONE);
                l2.setVisibility(View.VISIBLE);
                gettongji();
                getQyByDoc();
            }
        });

        cx2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gettongji();
                getQyByDoc();
            }
        });
    }

    //获取签约居民的信息

    public void getJumin(final String flag) {
        if (!NetWorkUtils.isNetworkConnected(context)) {
            MyToastUtil.ShowToast(context, "联网失败！");
        } else {
            RequestParams ps = new RequestParams();
            ps.add("token", SharedPreferencesUtils.getParam(context, "token", "").toString());
            ps.add("type", "2");
            ps.add("page", pageNum1 + "");
            ps.add("flag", flag);
            if (!StringUtils.isEmpty(key.getText().toString())) {
                ps.add("XINGMING", key.getText().toString());
            }
            if (!StringUtils.isEmpty(nf1)) {
                ps.add("nf", nf1);
            }

            UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                    MyToastUtil.ShowToast(context, "请求失败");
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                    String content = new String(response);
                    RetMsg ret = JSON.parseObject(content, RetMsg.class);
                    if (ret.getCode().equals("200")) {
                        if (pageNum1 == 1)
                            list = new ArrayList<JuMin>();
                        List<JuMin> ll = JSON.parseArray(ret.getList(), JuMin.class);
                        for (int i = 0; i < ll.size(); i++) {
                            list.add(ll.get(i));
                        }
                        listView.setSelection(list.size() - ll.size());
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getJumin(flag);
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getJumin(flag);
                            }
                        });
                        listView.setAdapter(new CommonAdapter<JuMin>(context, list, R.layout.jumin_item) {
                            @Override
                            public void convert(ViewHolder helper, JuMin item) {
                                if(flag.equals("0")) {
                                    helper.setText(R.id.name, item.getXINGMING());
                                }else{
                                    helper.setText(R.id.name, item.getXINGMING()+"("+DateConvert.dateToString(DateConvert.toDate(item.getCSRQ(), DateConvert.YMD), DateConvert.YMD) +")");
                                }
                                helper.setText(R.id.cardnum, item.getCARDNUM());
                                if(flag.equals("0")) {
                                    helper.setText(R.id.number, DateConvert.dateToString(DateConvert.toDate(item.getCSRQ(), DateConvert.YMD), DateConvert.YMD) + "    ");
                                }else{
                                    helper.setText(R.id.number, DateConvert.dateToString(DateConvert.toDate(item.getSignuptime(), DateConvert.YMD), DateConvert.YMD) + "    ");
                                }
                            }
                        });
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if(flag.equals("0")){
                                    //未签约
                                    Bundle b = new Bundle();
                                    b.putSerializable("juMin", list.get(position - 1));
                                    startActivity(new Intent(context, qianyue_add.class).putExtras(b).putExtra("type", "add"));
                                }else{
                                    //已签约
                                    Bundle b = new Bundle();
                                    b.putSerializable("juMin", list.get(position - 1));
//                                    startActivity(new Intent(context, qianyue_view.class).putExtras(b));
                                    startActivity(new Intent(context, qianyue_add.class).putExtras(b).putExtra("type", "edit"));
                                }

                            }
                        });
//                        for (int i = 0; i < ll.size(); i++) {
//                            List<JuMin> jlist = DataSupport.where("SFZH = ?", ll.get(i).getSFZH()).find(JuMin.class);
//                            if (jlist.size() > 0) {
//                                if (flag.equals("0"))
//                                    jlist.get(0).setIssign("1");//沒有签约
//                                else
//                                    jlist.get(0).setIssign("2");//已经签约
//                                jlist.get(0).update(jlist.get(0).getId());
//                            } else {
//                                Log.i("居民数据", "直接插入的数据");
//                                ll.get(i).setIsupdate("1");//设置不需要更新的操作
//                                if (flag.equals("0"))
//                                    ll.get(i).setIssign("1");//沒有签约
//                                else
//                                    ll.get(i).setIssign("2");//已经签约
//                                ll.get(i).save();
//                            }
//                        }
                    } else {
                        MyToastUtil.ShowToast(context, "获取错误");
                    }
                }

            });
        }
    }
    //获取统计信息
    public void gettongji() {
        RequestParams ps=new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(context,"token","").toString());
        ps.add("type","2");
        if (!StringUtils.isEmpty(nf2)) {
            ps.add("nf", nf2);
        }
        UserClient.get(HttpUrl.GetQyTj,ps,new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                JSONArray j=JSON.parseArray(ret.getRd());
                JSONObject js=j.getJSONObject(0);
                List<SliceValue> values = new ArrayList<SliceValue>();
                SliceValue sliceValue1 = new SliceValue(Float.parseFloat(js.getString("qySum")), colorData[1]);
                values.add(sliceValue1);
                SliceValue sliceValue2 = new SliceValue(Float.parseFloat(js.getString("wqySum")), colorData[0]);
                values.add(sliceValue2);
                pieChardata = new PieChartData();
                pieChardata.setHasLabels(true);//显示表情
                pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
                pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
                pieChardata.setHasCenterCircle(true);//是否是环形显示
                pieChardata.setValues(values);//填充数据
                pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
                pieChardata.setCenterCircleScale(0.5f);//设置环形的大小级别
                bzfx.setPieChartData(pieChardata);
                bzfx.setValueSelectionEnabled(true);//选择饼图某一块变大
                bzfx.setAlpha(0.9f);//设置透明度
                bzfx.setCircleFillRatio(1f);//设置饼图大小

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }
    public void getQyByDoc(){
        RequestParams ps=new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(this,"token","").toString());
        ps.add("type","2");
        if (!StringUtils.isEmpty(nf2)) {
            ps.add("nf", nf2);
        }
        UserClient.get(HttpUrl.GetQyByDoc,ps,new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                dlist=JSON.parseArray(ret.getRd(),Doctor.class);
                qylistView.setAdapter(new CommonAdapter<Doctor>(context,dlist,R.layout.doctor_item) {
                    @Override
                    public void convert(ViewHolder helper, Doctor item) {
                        helper.setText(R.id.name,item.getNickNameD());
                        helper.setText(R.id.gzdw,item.getNameD());
                        helper.setText(R.id.tjrs,item.getYqyrs());
                    }
                });

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }
}
